package com.fwtai.service.web;

import com.alibaba.fastjson2.JSONObject;
import com.fwtai.bean.PageFormData;
import com.fwtai.bean.UploadFile;
import com.fwtai.bean.UploadObject;
import com.fwtai.service.AsyncService;
import com.fwtai.tool.IdBuilder;
import com.fwtai.tool.ToolClient;
import com.fwtai.tool.ToolString;
import com.fwtai.web.ProductShowDao;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 产品展示业务层
 * @作者 田应平
 * @版本 v1.0
 * @QQ号码 444141300
 * @Email service@fwtai.com
 * @创建日期 2024-02-05 18:34:58
 * @官网 <url>http://www.fwtai.com</url>
*/
@Service
public class ProductShowService{

  @Value("${upload_dir_window}")
  private String dir_window;

  @Value("${upload_dir_linux}")
  private String dir_linux;

  private final AsyncService asyncService;

  private final ProductShowDao productShowDao;

  private final ThreadPoolTaskExecutor taskExecutor;

  public ProductShowService(final ProductShowDao productShowDao,final ThreadPoolTaskExecutor taskExecutor,final AsyncService asyncService){
    this.productShowDao = productShowDao;
    this.taskExecutor = taskExecutor;
    this.asyncService = asyncService;
  }

  public String add(final HttpServletRequest request){
    return CompletableFuture.supplyAsync(()->{
      final PageFormData formData = new PageFormData(request,4);
      final String p_title = "title";
      final String p_cover = "cover";
      final String p_details = "details";
      final String validate = ToolClient.validateField(formData,p_title,p_details);
      if(validate != null) return validate;
      final String len_title = formData.getString(p_title);
      if(len_title != null && len_title.length() > 128){
        return ToolClient.createJsonFail("标题（产品名称）字数太多");
      }
      final String len_details = formData.getString(p_details);
      if(len_details != null && len_details.length() > 921600000){
        return ToolClient.createJsonFail("产品展示详情字数太多");
      }
      final String baseDir = ToolString.isLinuxOS() ? dir_linux : dir_window;
      final UploadObject uploadObject = ToolClient.uploadFile(request,baseDir,"/product_show",false,1,3,new String[]{p_cover});
      final String errorMsg = uploadObject.getErrorMsg();
      if(errorMsg != null) return ToolClient.createJsonFail(errorMsg);
      final ArrayList<UploadFile> listFiles = uploadObject.getListFiles();
      formData.remove(p_cover);
      final boolean b = listFiles == null || listFiles.isEmpty();
      if(b) return ToolClient.createJsonFail("请选择上传文件");
      listFiles.forEach(uploadFile -> {
        final JSONObject json = new JSONObject(4);
        json.put("fullPath",uploadFile.getFullPath());
        json.put("urlFile",uploadFile.getUrlFile());
        json.put("fileSize",uploadFile.getFileSize());
        json.put("originalName",uploadFile.getOriginalName());
        json.put("currentDir",uploadFile.getCurrentDir());
        formData.put(p_cover,json.toJSONString());
      });
      final Integer sort = formData.getInteger("sort");
      if(sort != null){
        formData.put("sort",sort);
      }
      formData.put("kid",new IdBuilder().getId121L());//如以用户主键创建的表,可使用唯一键约束并结合IGNORE使用
      return ToolClient.executeRows(productShowDao.add(formData));
    },taskExecutor).join();
  }

  public String edit(final HttpServletRequest request){
    return CompletableFuture.supplyAsync(()->{
      final PageFormData formData = new PageFormData(request,3);
      final String p_kid = "kid";
      final String p_title = "title";
      final String p_cover = "cover";
      final String p_details = "details";
      final String validate = ToolClient.validateField(formData,p_kid,p_title,p_details);
      if(validate != null) return validate;
      final String len_title = formData.getString(p_title);
      if(len_title != null && len_title.length() > 128){
        return ToolClient.createJsonFail("标题（产品名称）字数太多");
      }
      final String len_details = formData.getString(p_details);
      if(len_details != null && len_details.length() > 921600000){
        return ToolClient.createJsonFail("产品展示详情字数太多");
      }
      final long kid = formData.getLong(p_kid);
      final HashMap<String,String> v = productShowDao.queryExistById(kid);
      if(v == null){
        return ToolClient.createJsonFail("数据不存在,刷新重试");
      }
      final String baseDir = ToolString.isLinuxOS() ? dir_linux : dir_window;
      final UploadObject uploadObject = ToolClient.uploadFile(request,baseDir,"/product_show",false,1,3,null);
      final String errorMsg = uploadObject.getErrorMsg();
      if(errorMsg != null) return ToolClient.createJsonFail(errorMsg);
      final ArrayList<UploadFile> listFiles = uploadObject.getListFiles();
      final boolean b = listFiles != null && !listFiles.isEmpty();
      formData.remove(p_cover);
      if(b){
        final ArrayList<String> lists = new ArrayList<>(1);
        lists.add(p_cover);
        asyncService.handlerFile(formData,listFiles,lists);//适用于json类型(单文件上传)
      }
      formData.put(p_kid,kid);
      final Integer sort = formData.getInteger("sort");
      if(sort != null){
        formData.put("sort",sort);
      }
      final int rows = productShowDao.edit(formData);
      if(rows > 0 && b){
        for(int y = listFiles.size() - 1; y >= 0; y--){
          final String fileName = listFiles.get(y).getName();
          for(final String key : v.keySet()){
            if(key.equals(fileName)){
              asyncService.delFileJsonObject(v.get(key));//删除单文件字段的文件
              break;
            }
          }
        }
      }
      return ToolClient.executeRows(rows);
    },taskExecutor).join();
  }

  public String queryById(final Long kid){
    return CompletableFuture.supplyAsync(()->{
      if(kid == null){
        return ToolClient.jsonValidateField();
      }
      return ToolClient.queryJson(productShowDao.queryById(kid));
    },taskExecutor).join();
  }

  //编辑时的文件删除可参考此方法
  public String delById(final Long kid){
    return CompletableFuture.supplyAsync(()->{
      if(kid == null){
        return ToolClient.jsonValidateField();
      }
      final HashMap<String,String> map = productShowDao.queryExistById(kid);
      if(map == null){// 此处map == null永远为true，所以map.isEmpty()永远为true，要非空时 if(map != null){}
        return ToolClient.createJsonFail("数据不存在,刷新重试");
      }
      final int rows = productShowDao.delById(kid);
      if(rows > 0){
        final ArrayList<String> lists = new ArrayList<>(1);//单文件上传的字段集
        lists.add("cover");
        for(int x = lists.size() - 1; x >= 0; x--){
          asyncService.delFileJsonObject(map.get(lists.get(x)));
        }
      }
      return ToolClient.executeRows(rows,"操作成功","删除失败,刷新重试");
    },taskExecutor).join();
  }

  public String delByKeys(final String ids){
    return CompletableFuture.supplyAsync(()->{
      if(ids == null || ids.length() == 0){
        return ToolClient.jsonValidateField();
      }
      final long[] list = ToolString.keysToArarry(ids);
      if(list == null){
        return ToolClient.createJsonFail("请选择要删除的数据");
      }
      final List<HashMap<String,String>> files = productShowDao.queryFiles(list);
      if(files.isEmpty()){// 此处的files == null永远不为true，所以验证非空时 if(!list.isEmpty()){}
        return ToolClient.createJsonFail("数据不存在,刷新重试");
      }
      final int rows = productShowDao.delByKeys(list);
      if(rows > 0){
        final ArrayList<String> lists = new ArrayList<>(1);
        lists.add("cover");
        for(int x = lists.size() - 1; x >= 0; x--){
          final String key = lists.get(x);
          for(int y = files.size() - 1; y >= 0; y--){
            final HashMap<String,String> map = files.get(y);
            for(final String k : map.keySet()){
              if(k.equals(key)){
                asyncService.delFileJsonObject(map.get(key));//视情况是否删除时连同删除文件
                break;
              }
            }
          }
        }
      }
      return ToolClient.executeRows(rows,"操作成功","数据不存在,刷新重试");
    },taskExecutor).join();
  }

  public String listData(final PageFormData formData){
    return CompletableFuture.supplyAsync(()->{
      try{
        if(ToolClient.dataTableMysql(formData) == null) return ToolClient.jsonValidateField();
        final CompletableFuture<List<HashMap<String,Object>>> listData = CompletableFuture.supplyAsync(() -> productShowDao.getListData(formData),taskExecutor);
        final CompletableFuture<Integer> listTotal = CompletableFuture.supplyAsync(() -> productShowDao.getListTotal(formData),taskExecutor);
        //CompletableFuture.allOf(listData,listTotal).join();//若出错取消注释即可
        return ToolClient.dataTableOK(listData.join(),listTotal.join());
      } catch (final Exception ignored){
        return ToolClient.dataTableException();
      }
    },taskExecutor).join();
  }
}